# -*- coding: utf-8 -*-
import json

from  method import *
import unittest,random,time,uuid
# from ddt import ddt,data,unpack,file_data
# @ddt
class test_employee_entry():

    def ready_(self,environment):
        global name
        global phone
        global conn
        global cursor
        global base_sql
        global evaluation_results_url
        if environment=='154':
            write_yaml(environment)
            conn = mysql('154')
            evaluation_results_url = '10032930'
        if environment=='uat':
            write_yaml(environment)
            conn = mysql('uat')
            evaluation_results_url = '10027731,10027732'
        cursor = conn.cursor()
        timestamp = int(time.time())
        name = random.choice(xing) + random.choice(ming)
        # name = random.choice(xing) + random.choice(ming) + random.choice(zimu)
        phone = '188' + str(timestamp)[2:10]
        base_sql=environment
        return name,phone,cursor

    #登录系统，取token
    def test_login(self):
        url = get_url('login')
        headers = get_headers('login')
        data=get_data('login')
        expect=get_expect('login')
        ree = send_requests('login', url, data, headers)
        a1 = json.loads(ree.text)
        # self.assertEqual(a1['status'], expect)
        token=a1['data']['token']
        return token

    #提交待入职信息、完成性格测评、背调
    def test_send_information(self):
        token=test_employee_entry().test_login()
        url = get_url('EntrantInfo')
        headers = get_headers('EntrantInfo')
        headers['Authorization']=token
        data=get_data('EntrantInfo')
        data['employeePhone']=phone
        data['employeeName']=name
        data['email']=phone +'@139.com'
        global clientId
        clientId=data['clientId']
        ree = send_requests('EntrantInfo', url, data, headers)
        a1 = json.loads(ree.text)
        # self.assertEqual(a1['status'], expect)
        sql1="select id from entrant where employee_phone='%s';"%(phone)
        cursor.execute(sql1)
        print('员工姓名：'+name)
        result=cursor.fetchall()
        for i in result:
            global id
            id=i[0]
        #完成性格测评
        sql2="INSERT INTO employee_personality_assessment(`personality_assessment_id`, `activity_id`, `entrant_id`, `evaluation_progress`, `evaluation_results`, `answer_url`, `evaluation_results_url`, `effective_time`, `expiration_time`, `email`, `cc`, `title`, `content`, `operator_id`, `is_deleted`, `gmt_create`, `gmt_modify`) VALUES (NULL, 958685, %s, 15, 0, 'https://derkee.ceping.com/Login/Elink?elink=hyGLkE7s3E7WNgd2MFSFscxOCbaMzxcChina25EigVVYMdsBvmYivCCZq/nP2M/zmtg5wBYZ65rhy', '%s', '2024-01-09 16:23:00', '2024-01-09 16:23:00', '', '', '', '', '007', 0, '2024-01-09 16:23:00', '2024-01-09 16:23:00');"%(id,evaluation_results_url)

        cursor.execute(sql2)
        conn.commit()
        #完成背调测评
        sql = "INSERT INTO emp_background_check (`background_id`, `entrant_id`, `back_status`, `risk_level`, `report_url`, `created_by`, `gmt_create`, `callback_time`, `cc`, `submit_time`, `number`, `completion_time`) VALUES (NULL, %s, 15, 4, 'https://lieni-file-test.oss-cn-hangzhou.aliyuncs.com/liechacha_common/20230609/10/c1f43f37-6d83-45b5-a390-d414d238abe8.pdf', '20280', '2024-01-17 15:03:11', '2024-01-17 15:03:11', '', '2024-01-17 15:03:11', '168846251718738121', 1688462519000);"%(id)
        cursor.execute(sql)
        conn.commit()
        #完成合同日期填补
        sql3="INSERT INTO employment_contract(`id`, `entrant_id`, `employee_id`, `contract_issue_date`, `start_date`, `stop_date`, `automatic_reminder`, `try_out_salary`, `positive_salary`, `operator_id`, `is_deleted`, `created_at`, `updated_at`, `deleted_at`, `template_serial`, `emp_contract_serial`, `emp_contract_status`, `operation_type`, `effective_contract`, `is_protocol`, `last_emp_contract_serial`, `emp_unit_price`) VALUES (NULL, %s, NULL, NULL, '2022-01-11', '2028-03-28', NULL, 9000.00, 10000.00, NULL, 0, NOW(),NOW(), NULL, '1800666d78134aaaaecf5d461fe81625', 'e3b7b082dc9f4c9e8bc0ec4992c95d73', 5, '10', NULL, NULL, '031faf67b9624aa8b17491acb6c50a2c', NULL);"%(id)
        cursor.execute(sql3)
        conn.commit()

        #完成社保、公积金方案
        global random_uuid
        # random_uuid = int(time.time()*1000)
        random_uuid=str(uuid.uuid4()).replace('-','')
        sql4="INSERT INTO empl_wage_scheme (`wage_scheme_id`, `employee_status`, `salary_calculate_way`, `com_unit_price`, `annual_bonus_type`, `city_of_social_type`, `city_of_social`, `ss_level_config_id`, `ss_pay_type`, `salary`, `gmt_create`, `gmt_modify`, `created_by`, `updated_by`, `is_deleted`, `entrant_id`, `work_province_code`, `work_city_code`, `work_area_code`,`hr_ss_pay_type`, `planned_admission_date`, `other_cost`, `other_cost_remark`) VALUES ('%s', 0, 1, 35152.25, 0, 1, 440300, 'SBGZ20240719001', 1, NULL, NOW(),NOW(), '20280', '20280', 0, %s, 440000, 440300, 440305, 1, '2024-09-09', 999.00,'其他成本备注');"%(random_uuid,id)
        cursor.execute(sql4)
        conn.commit()

        sql5="INSERT INTO empl_wage_scheme_detail (`wage_scheme_detail_id`, `wage_scheme_id`, `try_out_salary`, `positive_salary`, `social_security_base`, `provident_fund_base`, `entry_gross_profit`, `entry_gross_profit_margin`, `customer_minimum_gross_margin`, `ss_type`, `gmt_create`, `gmt_modify`, `created_by`, `updated_by`, `is_deleted`) VALUES (NULL, '%s', 15162.26, 18425.25, 2500.00, 15162.26, 8258.67, 23.49, 14.00, 1, NOW(), NOW(), '20280', '20280', 0);"%(random_uuid)
        cursor.execute(sql5)
        conn.commit()

        # 险金记录表中插入数据
        sql = ( "INSERT INTO wage_scheme_confirm_record (`wage_scheme_confirm_record_id`, `wage_scheme_id`, `ss_type`, `try_out_salary`, `positive_salary`, `social_security_base`, `provident_fund_base`, `confirm_channel`, `ip_address`, `gmt_create`, `gmt_modify`, `created_by`, `updated_by`, `is_deleted`, `entrant_id`) "
                "VALUES (NULL, '%s', 1, 15162.26, 18425.25, 2360.00, 15162.26, 2, '172.16.91.139', now(), now(), 'system', 'system', 0, %s);") % (
              random_uuid, id)
        cursor.execute(sql)
        conn.commit()

        print('数据已经提交&数据库操作完毕！')
        return id

    # 获取流程节点信息
    def audit_config(self,bizType,accountManagerId,clientId,attributionId,employeeId):
        token = test_employee_entry().test_login()
        url = get_url('getAuditConfig')
        headers = get_headers('getAuditConfig')
        headers['Authorization'] = token
        data = get_data('getAuditConfig')
        data['bizType'] = bizType
        data['accountManagerId'] = accountManagerId
        data['clientId'] = clientId
        data['attributionId'] = attributionId
        data['employeeId']=employeeId
        ree = send_requests('getAuditConfig', url, data, headers)
        a1 = json.loads(ree.text)
        auditConfigVO = a1['data']
        return auditConfigVO

    # hhx提交入职信息（相当于小程序扫码入职）
    def test_scanningcode(self):
        # token = test_employee_entry().test_login()
        url = get_url('EntrantInfo2')
        headers = get_headers('EntrantInfo2')
        # headers['Authorization'] = token
        data = get_data('EntrantInfo2')
        data['entrantId'] = id
        data['employeeName'] = name
        data['contactWay'] = phone
        ree = send_requests('EntrantInfo2', url, data, headers)
        a1 = json.loads(ree.text)
        # self.assertEqual(a1['status'], expect)


        print('小程序扫码入职完毕！')

    # 发起入职申请流程
    def test_application_process(self):
        token = test_employee_entry().test_login()
        #查询流程节点信息
        auditConfigVO = test_employee_entry().audit_config('29', '20280', clientId,1, None)
        #提交入职申请流程
        url = get_url('EntrantNewFlow')
        headers = get_headers('EntrantNewFlow')
        headers['Authorization'] = token
        data = get_data('EntrantNewFlow')
        data['entrantId'] = id
        data['employeeName'] = name
        data['contactWay'] = phone
        data['auditConfigVO']=auditConfigVO
        ree = send_requests('EntrantNewFlow', url, data, headers)
        a1 = json.loads(ree.text)
        # self.assertEqual(a1['status'], expect)
        print('入职流程申请完毕！')

    # 审批流程
    def test_approval_process(self):
        #查询流程编号
        sql4 = "SELECT flow_number FROM audit WHERE employee_name='%s' ORDER BY audit_id DESC LIMIT 1;"%(name)
        cursor.execute(sql4)
        conn.commit()
        result = cursor.fetchall()
        for i in result:
            flow_number = i[0]
        print('流程编号:' + str(flow_number))

        #调接口进行流程审批
        process_approval(flow_number=flow_number,environment=base_sql)

    # 生成合同
    def test_creat_contract(self):
        #查询员工工号
        sql7 = "SELECT employee_id FROM employee_info WHERE contact_way ='%s'" % (phone)
        cursor.execute(sql7)
        conn.commit()
        result = cursor.fetchall()
        for i in result:
            global employee_id
            employee_id = i[0]
        print('员工工号是：'+str(employee_id))

        #更新员工密码
        sql8 = "UPDATE employee_info SET password='$2a$10$0lbPGdjNzTK40DHiRtGiU.ekDMIZ16flo0ncQqaVUrzJ2vuNfLKYm' WHERE employee_id='%s'" % (employee_id)
        cursor.execute(sql8)
        conn.commit()
        token = test_employee_entry().test_login()
        url = get_url('generateContract')
        headers = get_headers('generateContract')
        headers['Authorization']=token
        data = get_data('generateContract')
        data[0]['employeeId']=employee_id
        data[0]['entrantId']=id
        data[0]['employeeName']=name
        ree1 = send_requests('generateContract', url, data, headers)
        a1 = json.loads(ree1.text)
        # self.assertEqual(a1['status'], expect)
        print('员工合同生成成功！')

    # 推送合同到小程序
    def test_send_contract(self):
        # 查询员工合同编号
        sql = "select emp_contract_serial from employment_contract where employee_id=%s;"% (employee_id)
        cursor.execute(sql)
        conn.commit()
        result = cursor.fetchall()
        for i in result:
            global emp_contract_serial
            emp_contract_serial = i[0]
        token = test_employee_entry().test_login()
        url = get_url('pushContract')
        headers = get_headers('pushContract')
        headers['Authorization'] = token
        data =get_data('pushContract')
        data[0]['employeeId'] = employee_id
        data[0]['entrantId'] = id
        data[0]['employeeName'] = name
        data[0]['empContractSerial']= emp_contract_serial
        ree1 = send_requests('pushContract', url, data, headers)
        a1 = json.loads(ree1.text)
        # self.assertEqual(a1['status'], expect)
        print('员工合同推送成功！')


        #查询员工合同编号
        sql="SELECT emp_contract_serial FROM labor_to_sign_employee WHERE employee_id =%s;"%(employee_id)
        cursor.execute(sql)
        conn.commit()
        result = cursor.fetchall()
        for i in result:
            emp_contract_serial = i[0]
        #完成合同表签约
        sql1="UPDATE labor_to_sign_employee SET contract_status=20,is_deleted=1  WHERE employee_id =%s;"%(employee_id)
        cursor.execute(sql1)
        conn.commit()
        # 新增员工签约合同
        sql2 = "INSERT INTO `labor_sign_employee` (`id`, `employee_id`, `emp_contract_serial`, `gmt_create`, `gmt_modify`, `operator_id`) \
                 VALUES (NULL, %s, '%s', now(), NULL, NULL);"%(employee_id,emp_contract_serial)
        cursor.execute(sql2)
        conn.commit()
        #更新合同表签署状态
        sql3 = "UPDATE employment_contract SET emp_contract_status=5 WHERE employee_id =%s;"%(employee_id)
        cursor.execute(sql3)
        conn.commit()

        print('员工合同签约完成！')

    #员工确认到岗
    def test_confirm_duty(self):
        token = test_employee_entry().test_login()
        url = get_url('updateEmplInfo')
        headers = get_headers('updateEmplInfo')
        headers['Authorization'] = token
        data =get_data('updateEmplInfo')
        data['employeeId'] = employee_id
        ree1 = send_requests('updateEmplInfo', url, data, headers)
        a1 = json.loads(ree1.text)
        # self.assertEqual(a1['status'], expect)
        print('员工确认到岗成功！')
    #员工入场、发起员工计费流程
    def test_GoAdmission(self):
        token = test_employee_entry().test_login()
        # 查询流程节点信息

        auditConfig = test_employee_entry().audit_config(30, None, clientId,None, employee_id)
        # 查询新入职待派遣员工ID
        sql = "SELECT dispatched_staff_id FROM dispatched_staff WHERE employee_id ='%s';" % (employee_id)
        cursor.execute(sql)
        conn.commit()
        result = cursor.fetchall()
        for i in result:
            dispatched_staff_id = i[0]

        url = get_url('ProcessOfGoAdmission')
        headers = get_headers('ProcessOfGoAdmission')
        headers['Authorization'] = token
        data = get_data('ProcessOfGoAdmission')
        data['employeeId'] = employee_id
        data['employeeName']=name
        data['dispatchedStaffId']=dispatched_staff_id
        data['auditConfig']=auditConfig
        ree1 = send_requests( 'ProcessOfGoAdmission', url, data, headers)
        a1 = json.loads(ree1.text)
        print('发起员工计费流程成功！')
        # 查询流程编号
        sql5 = "SELECT flow_number FROM  audit  WHERE  audit_status=0 AND employee_id='%s';"%(employee_id)
        # print(employee_id)
        cursor.execute(sql5)
        conn.commit()
        result = cursor.fetchall()
        for i in result:
            flow_number = i[0]
        print('流程编号:' + str(flow_number))
        # 调接口进行流程审批
        process_approval(flow_number=flow_number,environment=base_sql)



    def test_billing_process(self):
        print('自动化操作部分已经执行完毕,请去小程序完成合同签订、PC端法人盖章等操作，后续操作敬请期待...')


if __name__=="__main__":

        start_time = time.time()   # 记录开始时间
        # 这里写需要测试运行时间的代码
        for i in range(1):
            test_employee_entry().ready_('154')
            # test_employee_entry().ready_('uat')
            test_employee_entry().test_send_information()
            test_employee_entry().test_scanningcode() # hhx提交入职信息（相当于小程序扫码入职）
            # test_employee_entry().test_application_process()
            # test_employee_entry().test_approval_process()
            # test_employee_entry().test_creat_contract()
            # test_employee_entry().test_send_contract()
            # test_employee_entry().test_confirm_duty()
            # test_employee_entry().test_GoAdmission()
            # test_employee_entry().test_billing_process()
        end_time = time.time()   # 记录结束时间
        run_time = end_time - start_time    # 计算运行时间（单位为秒）
        print("脚本运行时间：", round(run_time, 2), '秒')
















